<template>
  <div class="Box">
    <mt-header
      title="购物车"
      style="
        background-color: rgb(248, 62, 62);
        font-size: 18px;
        font-family: Georgia;
      "
    ></mt-header>

    <!-- 购物车空空 -->
    <div class="goShopping" v-if="!car.length">
      <div>
        <img width="80%" src="../assets/购物车空空.jpg" alt="" />
      </div>
      <div>
        <router-link to="/product">
          <button class="btn">去购物</button>
        </router-link>
      </div>
    </div>
    <!-- 卡片 -->
    <ul v-else style="margin-bottom: 110px">
      <div v-if="isReloadData">
        <li
          style="background-color: rgb(245, 243, 243)"
          v-for="(item, i) in car"
          :key="i"
        >
          <van-checkbox-group v-model="checked" ref="checkboxGroup">
            <div class="big">
              <van-checkbox @click="checkOne(item.id)"></van-checkbox>
              <div class="tou">
                <span class="icon_gou"></span>
                <span style="color: black">{{ item.title }}</span>
              </div>
              <div class="dwd">
                <router-link :to="`/product_details?id=${item.id}`">
                  <div class="tu">
                    <img :src="`${item.photo}`" alt="" />
                  </div>
                </router-link>
                <div class="wen">
                  <router-link :to="`/product_details?id=${item.id}`">
                    <p id="p2">
                      {{ item.slogan }}
                    </p>
                  </router-link>
                  <div class="qian">
                    <span id="p1">￥{{ item.price }}</span>
                    <div class="add">
                      <van-stepper
                        v-model="obj[item.id]"
                        theme="round"
                        button-size="22"
                        min="1"
                        disable-input
                        @plus="add(item.id, item.price, 'PLUS')"
                        @minus="down(item.id, item.price, 'MINUS')"
                      />
                    </div>
                  </div>
                  <!-- 删除垃圾桶 -->
                  <div
                    class="clear"
                    @click="showDelete(item.id, item.price, item.count)"
                  >
                    <img width="100%" src="../assets/删除.svg" alt="" />
                  </div>
                </div>
              </div>
            </div>
          </van-checkbox-group>
        </li>
      </div>
      <div id="app">
        <van-submit-bar
          :loading="loading"
          :price="totalPrice"
          :button-text="`结算(${totalMount})`"
          @submit="onSubmit"
          bottom="50px"
        >
          <van-checkbox v-model="AllChecked" type="primary" @click="checkAll"
            >全选</van-checkbox
          >
        </van-submit-bar>
      </div>
    </ul>

    <!-- 底部Tabbar -->
    <mt-tabbar
      v-model="tabbars"
      fixed
      style="color: #bfbfbf; border-top: 1px solid #bfbfbf"
    >
      <mt-tab-item id="首页" style="background-color: #fff">
        <img slot="icon" src="../assets/首页.svg" />
        <strong>首页</strong>
      </mt-tab-item>
      <mt-tab-item id="周边" style="background-color: #fff">
        <img slot="icon" src="../assets/商城.svg" />
        <strong>周边</strong>
      </mt-tab-item>
      <mt-tab-item id="购物车" style="background-color: #fff">
        <img slot="icon" src="../assets/购物车(1).svg" />
        <strong style="color: rgb(248, 62, 62)">购物车</strong>
      </mt-tab-item>
      <mt-tab-item id="我的" style="background-color: #fff">
        <img slot="icon" src="../assets/我的.svg" />
        <strong>我的</strong>
      </mt-tab-item>
    </mt-tabbar>
  </div>
</template>
<style scoped>
/* .deleteText{
  position: fixed;
  width: 50%;
  height: 20%;
  z-index: 100;
  background-color: #999;
} */
.goShopping {
  position: relative;
  top: 90px;
}
.btn {
  width: 80%;
  height: 40px;
  border-radius: 20px;
  background-color: rgb(252, 114, 114);
  border: 0;
  color: white;
}
li {
  width: 95%;
  margin: auto;
  border: 1px solid rgb(245, 243, 243);
  margin-top: 10px;
  position: relative;
  border-radius: 15px;
  background-color: white;
}
.wen {
  width: 60%;
  text-align: left;
  float: right;
  /* background-color: blueviolet; */
}
.qian {
  position: absolute;
  bottom: 5%;
  right: 25%;
}
.qian span {
  display: inline-block;
  margin-top: 10px;
}
.qian .add {
  display: inline-block;
  position: relative;
  bottom: 5px;
  left: 30%;
}
.dwd::after {
  content: "";
  display: block;
  clear: both;
}
.big {
  margin-top: 10px;
  margin-left: 20px;
  width: 90%;
  height: 140px;
  /* background-color: aqua; */
}
.tou {
  text-align: left;
  position: absolute;
  top: 9px;
  left: 14%;
}
.tu {
  width: 100px;
  float: left;
  position: absolute;
  top: 40px;
}
.tu > img {
  display: inline-block;
  width: 100%;
  height: 95px;
  /* margin-right: 220px; */
  /* border: 1px solid rgb(226, 224, 224); */
  /* background: black; */
}
#p2 {
  margin: 0;
  margin-top: 10%;
  font-size: 14px;
  color: rgb(109, 107, 107);
}
#p1 {
  position: relative;
  left: 20%;
  color: rgb(247, 15, 15);
}
#app /deep/ .van-submit-bar {
  bottom: 56px;
}
#app /deep/ .van-submit-bar__button {
  width: 38%;
}
.clear {
  width: 20px;
  position: absolute;
  right: 5%;
  bottom: 7%;
}
</style>
<script>
import axios from "axios";
import { mapActions, mapState } from "vuex";
import { mapGetters } from "vuex";
export default {
  data() {
    return {
      tabbars: "购物车",
      checked: [],
      isReloadData: true,
      AllChecked: false,
      loading: false,
      obj: {},
      count: 0,
      tprice: 0,
      arr1: [],
    };
  },
  watch: {
    //底部导航跳转
    tabbars() {
      if (this.tabbars == "周边") {
        this.$router.push("/product");
      } else if (this.tabbars == "首页") {
        this.$router.push("/");
      } else if (this.tabbars == "我的") {
        this.$router.push("/me");
      }
    },
    //监听
  },
  methods: {
    //发请求 获取商品数据
    product() {
      axios
        .get(`get_user_cart?userid=${this.$store.state.userid}`)
        .then((res) => {
          let arr = res.data.result;
          for (var i = 0; i < arr.length; i++) {
            // console.log(arr[i].pid)
            this.arr1.push(arr[i].pid);
            this.tprice += arr[i].tprice * 100;
            this.count += arr[i].num;
          }
          this.obj = this.arr1.reduce(function (a, b) {
            if (b in a) {
              a[b]++;
            } else {
              a[b] = 1;
            }
            return a;
          }, {});
          // console.log(this.obj)   //obj.1==2    obj.7==1
        });
    },
    // ...mapMutations(['reduceGood']),
    ...mapActions(["reduceGood", "addGood", "removeGood"]),
    //减少商品数量
    down(id, price, type) {
      this.reduceGood(id);
      this.$store.dispatch("setTotal", {
        type: type,
        price: Number(price),
      });
    },
    //增加商品数量
    add(id, price, type) {
      this.addGood(id);
      this.$store.dispatch("setTotal", {
        type: type,
        price: Number(price),
      });
    },
    //删除商品(localStorage、列表、数据库)
    showDelete(id, price, mount) {
      this.$dialog
        .alert({
          // title: "删除", //加上标题
          message: "确认将这个宝贝删除？", //改变弹出框的内容
          showCancelButton: true, //展示取消按钮
        })
        .then(() => {
          //点击确认按钮后的调用\
          this.$store.dispatch("removeGood", {
            id,
            price: Number(price),
            mount: Number(mount),
          });
          this.deleteSql(id);
        })
        .catch(() => {
          //点击取消按钮后的调用
          console.log("点击了取消按钮噢");
        });
    },
    //删除  在数据库中删除 用户下对应商品的数据
    deleteSql(pid) {
      axios
        .post(
          "/delete_user_cart",
          `userid=${this.$store.state.userid}&pid=${pid}`
        )
        .then((res) => {
          // console.log(res)
        });
    },
    //商品加入购物车时 默认为选中状态
    // check(val) {
    //   console.log(val)
    //   if(this.$store.islogin==true){
    //     let checked = [];
    //     let len = JSON.parse(window.localStorage.car).length;
    //     for (var i = 0; i < len; i++) {
    //       checked.push(i);
    //     }
    //     this.checked = checked;
    //   }

    // },
    //单选
    checkOne(id) {
      // console.log(id);
      console.log(this.checked);
      if (this.checked.indexOf(id) > -1) {
        this.checked.remove(id);
        console.log(this.checked);
      } else {
        this.checked.push(id);
      }
      if (this.checked.length) {
      }
    },
    //点击全选的时候
    checkAll() {
      let len = JSON.parse(window.localStorage.car).length;
      let cLen = this.checked.length;
      if (cLen == len) {
        //复选框长度 等于 car的长度时    点击全选应取消
        this.checked = []; //即清空复选框
        // window.localStorage.totalMount=0;
      } else if (cLen == 0 || (cLen > 0 && cLen < len)) {
        //当复选框没选 或 选择其中一两个   点击全选 应 全部选择
        this.check(); //调用函数   默认全部为选中状态
        this.selectAll = true;
      }
    },

    //结算商品
    onSubmit() {
      this.loading = true;
      setTimeout((res) => {
        this.loading = false;
        this.$router.push("/order");
      }, 1000);
    },
  },
  mounted() {
    this.product();
    // this.check();
    // this.handleCheckAll()
  },
  computed: {
    ...mapState(["car", "totalMount", "totalPrice"]),
    ...mapGetters(["getAllCount", "getAllPrice"]),
  },
};
</script>
